package com.ylyq.ylxx.service.impl;

import com.google.common.collect.Lists;
import com.ylyq.ylxx.service.IFileService;
import com.ylyq.ylxx.util.Tools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @ClassName IFileServiceImpl
 * @Description TODO
 * @Author xiaweichao
 * @Date 2020/7/9 13:51
 * @Version 1.0
 */
@Slf4j
@Service
public class FileServiceImpl implements IFileService {
    @Value("${public.config.fileUploadPath}")
    private String fileUploadPath;
    @Value("${public.config.fileDownloadPath}")
    private String fileDownloadPath;
    @Value("${public.config.fileUploadDir}")
    private String fileUploadDir;
    @Value("${server.port}")
    private int serverPort;
    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Override
    public String uploadPhotoOrFile(MultipartFile file) throws UnknownHostException {

        // 首先校验图片格式
        List<String> imageType = Lists.newArrayList("jpg", "jpeg", "png", "bmp", "gif");
        // 首先校验音频格式
        List<String> audioType = Lists.newArrayList("CD", "WAVE", "AIFF", "MPEG", "MP3", "MPEG-4", "MIDI", "WMA", "RealAudio", "VQF", "OggVorbis", "AMR", "APE", "FLAC", "AAC","NCM");
        // 获取文件名，带后缀
        String originalFilename = file.getOriginalFilename().replace(" ","");//去掉空格
        // 获取文件的后缀格式
        String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
        //文件上传
        // 重新赋名，防止出现名称重复的情况
        String newFileName = Tools.getCurrentDate("yyyy-MM-dd-HH-mm-ss") + new Random().nextInt() + originalFilename;
        String path = (imageType.contains(fileSuffix) ? "uploadImg" : audioType.contains(fileSuffix.toUpperCase()) ? "uploadAudio" : "uploadFile") + "/" + newFileName;

        String ip = InetAddress.getLocalHost().getCanonicalHostName();
        //根据相对获取绝对路径(文件上传到的保存位置)
        File destFile = new File(fileUploadPath + path);
        if (!destFile.getParentFile().exists()) {
            destFile.getParentFile().mkdirs();
        }
        if (destFile.exists()) {
            //已存在
            log.error("文件已存在");
            return null;
        }
        try {
            file.transferTo(destFile);
//            String host =Tools.getAddress()+path;
            return fileDownloadPath + path;
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return null;
    }

    public String uploadPhotoOrFiletemp(MultipartFile file) throws UnknownHostException {

        // 首先校验图片格式
        List<String> imageType = Lists.newArrayList("jpg", "jpeg", "png", "bmp", "gif");
        // 获取文件名，带后缀
        String originalFilename = file.getOriginalFilename();
        // 获取文件的后缀格式
        String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
        //文件上传
        // 重新赋名，防止出现名称重复的情况
        String newFileName = Tools.getCurrentDate() + originalFilename;
//        String path = "/upload/" + (imageType.contains(fileSuffix) ? "uploadImg" : "uploadFile") + "/"+ newFileName;
        String path = fileUploadDir + (imageType.contains(fileSuffix) ? "uploadImg" : "uploadFile") + "/" + newFileName;

        String dirPath = "";
        String host = "";
        String ip = InetAddress.getLocalHost().getCanonicalHostName();
        if (InetAddress.getLocalHost().getHostAddress().startsWith("192.168")) {//本地
            // 该方法返回的为当前项目的工作目录，即在哪个地方启动的java线程
            dirPath = System.getProperty("user.dir") + "/ylyq/src/main/resources/static";
            host = "http://" + InetAddress.getLocalHost().getHostAddress() + ":" + serverPort + contextPath + path;
        } else {
            dirPath = System.getProperty("user.dir") + "/ylyq";
            host = "http://39.108.10.98" + path;
        }
        //根据相对获取绝对路径(文件上传到的保存位置)
        File destFile = new File(dirPath + path);
        if (!destFile.getParentFile().exists()) {
            destFile.getParentFile().mkdirs();
        }
        if (destFile.exists()) {
            //已存在
            log.error("文件已存在");
            return null;
        }
        try {
            file.transferTo(destFile);
//            String host =Tools.getAddress()+path;
            return host;
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return null;
    }

    /*
     * @Author xiaweichao
     * @Description //上传文件或照片
     * @Param [files]
     * @return com.oacloud.common.model.ResponseData
     **/
    @Override
    public List<String> uploadPhotoOrFiles(MultipartFile[] files) throws UnknownHostException {
        List<String> pathList = new ArrayList<>();
        for (MultipartFile file : files) {
            String s = uploadPhotoOrFile(file);
            // 将相对路径保存
            pathList.add(s);
        }
        return pathList;
    }

}
